import java.io.*;
import java.util.*;
import javax.comm.*;

public class Dialup implements Runnable,SerialPortEventListener 
{

	static CommPortIdentifier portId;
	static Enumeration portList;

	InputStream inputStream;
	OutputStream outputStream;
	SerialPort serialPort;
	Thread dialupThread;
	String telNo;
	String dialCommand;
	String initCommand;
	String line;
	static BufferedReader bos;
	static OutputStream fos = null;
	static FileOutputStream output = null;
	static DataOutputStream dOut = null;
	boolean flag = false;
	int conCount = 0;

	public static void main(String[] args) 
	{
		try
		{
			fos = new FileOutputStream("dem.txt",true);
			bos = new BufferedReader(new FileReader("dem.txt"));
			output = new FileOutputStream("abc.txt",true);
			dOut = new DataOutputStream(output);
		}catch(Exception e)
		{}

		if( args.length != 1 ) 
		{
			System.err.println("Usage: Dialup ");
			return;
		}
		portList = CommPortIdentifier.getPortIdentifiers();

		while (portList.hasMoreElements()) 
		{
			portId = (CommPortIdentifier) portList.nextElement();
			if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) 
			{
				if (portId.getName().equals("COM1")) 
				{
					Dialup dialer = new Dialup(args[0]);
				}
			}
		}

	}

	public Dialup(String telNo) 
	{
//		this.dialCommand = "&F&K3%E2%C0W2\\N3+MS=12,1,28000,46667";
		this.telNo = telNo;
		this.dialCommand = "ATDT"+telNo+"\r";
		initCommand = "&F&K3%E2%C0W2\\N3+MS=12,1,28000,46667\r";
//		this.dialCommand = "AT&C0&W0\r";
//		this.dialCommand = "ATO0";
//		this.dialCommand = "ATO0";
		try 
		{
			serialPort = (SerialPort) portId.open("DialUp", 2000);
		}
		catch (PortInUseException e) 
		{
		}

		try 
		{
			inputStream = serialPort.getInputStream();
			outputStream = serialPort.getOutputStream();
		}
		catch (IOException e) 
		{
			System.out.println(" Hell " + e);
		}

		try 
		{
			serialPort.addEventListener(this);
		}
		catch (TooManyListenersException e) {
		}
	
	
	portList = CommPortIdentifier.getPortIdentifiers();
		while (portList.hasMoreElements()) 
		{
			portId = (CommPortIdentifier) portList.nextElement();

			if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) 
			{

				if (portId.getName().equals("COM1")) 
				{
//					System.out.println(getInputBufferSize());
//					try 
//					{
						//serialPort = (SerialPort) portId.open("writereadApp", 2100);
						//System.out.println("Opened the port for writing: " + portId.getName());
//					}
//					catch (PortInUseException e) {System.out.println("IN USE ----  " + e);}			

					try 
					{
						serialPort.setSerialPortParams(9600,
						SerialPort.DATABITS_8,
						SerialPort.STOPBITS_1,
						SerialPort.PARITY_NONE);
					}
					catch (UnsupportedCommOperationException e) 
						{
							System.out.println("UnsupportedCommOperationException, Could not write to the port: " + e);
						}
					try 
					{
						outputStream = serialPort.getOutputStream();
						inputStream = serialPort.getInputStream();
					} 
					catch (IOException e) {System.out.print(e);}

/*					try 
					{
						serialPort.addEventListener(this);
					} 
					catch (TooManyListenersException e) {System.out.println("TOOO " + e);}
*/
					serialPort.notifyOnDataAvailable(true);
					serialPort.notifyOnCarrierDetect(true);
					serialPort.notifyOnDataAvailable(true);
					serialPort.notifyOnBreakInterrupt(true);
					serialPort.notifyOnCTS(true);
					serialPort.notifyOnDSR(true);
					serialPort.notifyOnFramingError(true);
					serialPort.notifyOnOutputEmpty(true);
					serialPort.notifyOnOverrunError(true);
					serialPort.notifyOnParityError(true);
					serialPort.notifyOnRingIndicator(true);
				}

			}
		}
		dialupThread = new Thread(this);
		dialupThread.start();
	}

	public void run() 
	{
		while(true)
		{
			if(conCount == 0) 
			{
				try 
				{
					if( !serialPort.isCD() ) 
					{
	//					outputStream.write(initCommand.getBytes());
						System.err.println("Try to connect ...");
						outputStream.write(dialCommand.getBytes());
					}
					Thread.sleep(60000);
					/*for(int i=0; i < 10; i++)
					{
						outputStream.write("Ram".getBytes());
						System.out.print("Ram");
					}*/
				}
				catch(Exception ex) 
				{
					System.err.println("Failed to write message");
				}
			}
		}
	}

	public void serialEvent(SerialPortEvent event) 
	{
	switch(event.getEventType()) 
	{
		case SerialPortEvent.OE:
		case SerialPortEvent.FE:
		case SerialPortEvent.PE:
		case SerialPortEvent.DSR:
			System.out.println("Data Set Ready.");
			break;
		case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
			System.out.println("Ignored event");
			break;

		case SerialPortEvent.BI:
			System.out.println("Break Interrupt");
			break;

		case SerialPortEvent.CTS:
			System.out.println("Clear to send");
			break;


		case SerialPortEvent.RI:
			if( event.getNewValue() ) 
			{
				System.out.println("Ring Indicator On");
			}
			else 
			{
				System.out.println("Ring Indicator Off");
			}
			break;

		case SerialPortEvent.CD:
			if( event.getNewValue() ) 
			{
				System.out.println("Connected");
				conCount = conCount + 1;
				flag = true;
			}
			else 
			{
				System.out.println("Disconnected");
			}
			break;

		case SerialPortEvent.DATA_AVAILABLE:
			handleData();	
			break;
		}
	}

	public void handleData()
	{
		try
		{
			int avail = inputStream.available();
			byte[] response = new byte[avail];
			StringBuffer strbuf = new StringBuffer();
			inputStream.read(response, 0, avail);
			for (int i = 0; i < avail; i++) 
			{
				if(!flag)
				{
					fos.write((char)response[i]);
				}
			}
/*						while((line = bos.readLine())!=null)
			{
				if(line.equals("CONNECT 9600"))
				{
					flag = true;
					dOut.flush();								
				}
			}
*/			if(flag)
			{
				inputStream.read(response, 0, avail);
				for (int i = 0; i < avail; i++) 
				{
					Thread.sleep(5);
					output.write((char)response[i]);
					System.out.print((char)response[i]);
				}
			}
		}catch(IOException ie1){System.out.println("File " +ie1);}
		catch(InterruptedException in){System.out.println("Interrupt " +in);}

	}
}